package com.alibaba.csp.sentinel.dashboard.rule.convert;

import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.AuthorityRuleEntity;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.DegradeRuleEntity;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.RuleEntity;
import com.alibaba.csp.sentinel.dashboard.discovery.AppInfo;
import com.alibaba.csp.sentinel.dashboard.discovery.MachineInfo;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.slots.block.AbstractRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author: shaozeming
 * @date: 2022/8/8 19:50
 * @description:
 **/
public abstract class AbstractRuleConverter implements RuleConverter {

    @Override
    public Converter<String, List<RuleEntity>> ruleEntityDecoder(AppInfo appInfo) {
        ArrayList<MachineInfo> machineList = new ArrayList<>(appInfo.getMachines());
        return s -> Optional.ofNullable(s)
                .map(rules -> JSON.parseArray(rules, getRuleClass()))
                .map(rules -> rules.stream()
                        .map(e -> fromRule(e,appInfo,machineList))
                        .collect(Collectors.toList()))
                .orElse(null);
    }

    abstract Class<? extends AbstractRule> getRuleClass();


   abstract RuleEntity fromRule(AbstractRule abstractRule,AppInfo appInfo,List<MachineInfo> machineInfoList);
}

